<template>
  <div class="app-container">
    <el-tabs v-model="activeName">
      <el-tab-pane :key="'spectrum-data'" label="频谱数据" name="spectrum-data">
        <!-- <el-row> -->
        <el-col :span="16" class="left-condition">
          <div id="nate" style="width: 58vw; height: 60vh"></div>
          <!-- <div id="occupancy" style="width: 60vw; height: 30vh"></div> -->
        </el-col>

        <el-col :span="8" class="right-condition">
          <el-form
            ref="requestForm"
            :inline="false"
            :rules="rules"
            :model="formItem"
            label-width="120px"
          >
            <el-form-item label="请选择设备:">
              <el-select
                v-model="formItem.mfid"
                style="width: 220px"
                @change="refreshBoxStatus($event)"
              >
                <el-option
                  v-for="item in boxInfos"
                  :key="item.equid"
                  :label="item.mfid"
                  :value="item.mfid"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="起始频率:" prop="startfreq">
              <el-input
                v-model="formItem.startfreq"
                type="text"
                :disabled="ifEditable"
                placeholder=""
                style="width: 220px"
              >
                <i slot="suffix" style="font-style: normal; margin-right: 10px">
                  /{{ freqUnit }}
                </i>
              </el-input>
            </el-form-item>

            <el-form-item label="终止频率:" prop="stopfreq">
              <el-input
                v-model="formItem.stopfreq"
                :disabled="ifEditable"
                type="text"
                placeholder=""
                style="width: 220px"
              >
                <i slot="suffix" style="font-style: normal; margin-right: 10px">
                  /{{ freqUnit }}
                </i>
              </el-input>
            </el-form-item>

            <el-form-item label="RBW:" prop="step">
              <el-input
                v-model="formItem.step"
                :disabled="ifEditable"
                type="text"
                placeholder=""
                style="width: 220px"
              >
                <i slot="suffix" style="font-style: normal; margin-right: 10px">
                  /{{ stepUnit }}
                </i>
              </el-input>
              <!-- <el-select v-model="formItem.step" style="width: 220px">
                <el-option
                  v-for="item in stepList"
                  :key="item.id"
                  :label="item.val"
                  :value="item.id"
                ></el-option>
              </el-select> -->
            </el-form-item>

            <el-form-item v-show="!ifView">
              <el-button
                v-show="ifNormalUserHide"
                :disabled="isStartBtnDisabled"
                type="primary"
                @click="start"
              >
                启动
              </el-button>
              <el-button
                v-show="ifNormalUserHide"
                type="danger"
                :disabled="isStopBtnDisabled"
                @click="cmdStop"
              >
                停止
              </el-button>
              <el-button
                :disabled="isStopBtnDisabled"
                type="danger"
                @click="stop"
              >
                断开
              </el-button>
            </el-form-item>

            <el-form-item v-show="ifView">
              <el-button
                :disabled="isStartBtnDisabled"
                type="primary"
                @click="start"
              >
                查看
              </el-button>
              <el-button
                v-show="ifNormalUserHide"
                type="danger"
                :disabled="isStopBtnDisabled"
                @click="cmdStop"
              >
                停止
              </el-button>
              <el-button
                :disabled="isStopBtnDisabled"
                type="danger"
                @click="stop"
              >
                断开
              </el-button>
            </el-form-item>

            <!-- <el-form-item>
              <jamming-signal></jamming-signal>
            </el-form-item> -->

            <el-form-item>
              <div class="w100p flex">
                <div class="earn-title">总传输量</div>
              </div>
              <div class="w100p mt10">
                <div class="title-bottom-line ml1p"></div>
              </div>
              <!-- <div class="w96p mt10"></div> -->
              <div class="w100p mt10 flex">
                <div class="w100p flex">
                  <div class="w33p ring-name">频谱数据量</div>
                  <div class="w33p ring-name">IQ数据量</div>
                  <!-- <div class="w33p ring-name">占用度数据量</div> -->
                </div>

                <div class="w33p ring-numbers">
                  {{ spectrumNums.toLocaleString() }}KB
                </div>
                <div class="w33p ring-numbers">
                  {{ iqNums.toLocaleString() }}KB
                </div>
                <!-- <div class="w33p ring-numbers">{{ occupancyNums }}KB</div> -->
              </div>
            </el-form-item>
          </el-form>
        </el-col>
        <!-- </el-row> -->
      </el-tab-pane>

      <!-- <el-tab-pane :key="'iq-data'" label="IQ数据" name="iq-data">
        <el-col :span="16" class="left-condition">
          <div id="iq" style="width: 58vw; height: 60vh"></div>
        </el-col>

        <el-col :span="8" class="right-condition">
          <el-form :inline="false" label-width="120px">
            <el-form-item label="单频测量:" prop="freqSingleMeasureVal">
              <el-input
                v-model="freqSingleMeasureVal"
                type="text"
                disabled
                placeholder=""
                style="width: 220px"
              >
                <i slot="suffix" style="font-style: normal; margin-right: 10px">
                  /{{ freqUnit }}
                </i>
              </el-input>
            </el-form-item>

            <el-form-item label="请选择设备:">
              <el-select
                v-model="iqMfid"
                style="width: 220px"
                @change="refreshBoxStatus($event)"
              >
                <el-option
                  v-for="item in boxInfos"
                  :key="item.equid"
                  :label="item.mfid"
                  :value="item.mfid"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item>
              <el-button
                v-show="ifNormalUserHide"
                :disabled="isStartIQDisabled"
                type="primary"
                @click="startIQ"
              >
                启动
              </el-button>
              <el-button
                v-show="ifNormalUserHide"
                :disabled="isStopIQDisabled"
                type="danger"
                @click="stopIQ"
              >
                停止
              </el-button>
              <el-button type="warning" @click="resume">返回</el-button>
            </el-form-item>

            <el-form-item>
              <div class="w100p flex">
                <div class="earn-title">总传输量</div>
              </div>
              <div class="w100p mt10">
                <div class="title-bottom-line ml1p"></div>
              </div>
              <div class="w100p mt10 flex">
                <div class="w100p flex">
                  <div class="w33p ring-name">频谱数据量</div>
                  <div class="w33p ring-name">IQ数据量</div>
                </div>

                <div class="w33p ring-numbers">
                  {{ spectrumNums.toLocaleString() }}KB
                </div>
                <div class="w33p ring-numbers">
                  {{ iqNums.toLocaleString() }}KB
                </div>
              </div>
            </el-form-item>
          </el-form>
        </el-col>
      </el-tab-pane> -->
    </el-tabs>
  </div>
</template>

<script>
// import * as Echarts from 'echarts/lib/echarts'
import { mapGetters } from 'vuex'
import axios from 'axios'
import { isEmpty, sizeOfByte } from '@/utils/validate'
// import JammingSignal from "../components/jammingSignal";
let ws = null
let wsIQ = null
let intervalId = null
let heartHandler = null
let lineChart = null
let iqLineChart = null
export default {
  name: 'Nate',
  components: {
    // JammingSignal,
  },
  data: () => {
    const isNum = (rule, value, callback) => {
      const age = /^[1-9]\d*$/;
      if (!age.test(value)) {
        callback(new Error("必须为正整数"));
      } else {
        callback();
      }
    }
    return {
      ifNormalUserHide: true,
      ifEditable: true,
      mfid: 0,
      occupancyNums: 0,
      iqNums: 0,
      iqMfid: 0,
      freqSingleMeasure: 101400000,
      freqSingleMeasureVal: 101.4,
      spectrumNums: 0,
      selected: '',
      list: [],
      //默认显示频谱数据
      activeName: 'spectrum-data',
      ifView: false,
      showSpecData: true,
      showWsData: false,
      isStartIQDisabled: false,
      isStopIQDisabled: false,
      isStartBtnDisabled: false,
      isStopBtnDisabled: true,
      formItem: {
        mfid: 0,
        startUnit: '',
        startfreq: 80,
        stopfreq: 110,
        endUnit: '',
        step: '',
      },
      rules: {
        startfreq: [
          {
            required: true,
            message: "请输入起始频率",
            trigger: "blur"
          },
          {
            validator: isNum,
            trigger: "blur"
          }
        ],
        stopfreq: [
          {
            required: true,
            message: "请输入终止频率",
            trigger: "blur"
          },
          {
            validator: isNum,
            trigger: "blur"
          }
        ],
        step: [
          {
            required: true,
            message: "请输入RBW",
            trigger: "blur"
          },
          {
            validator: isNum,
            trigger: "blur"
          }
        ]
      },
      stepList: [
        {
          id: 25,
          val: '25kHz',
        },
        {
          id: 50,
          val: '50kHz',
        },
        {
          id: 100,
          val: '100kHz',
        },
      ],
      freqUnit: 'Mhz',
      stepUnit: 'hz',
      orgOptions: {},
      iqLineOptions: {},
      scatterOptions: {},
      occupancyOptions: {},
      boxInfos: []
    }
  },
  computed: {
    ...mapGetters({
      username: 'user/username',
      permissions: 'user/permissions',
    }),
  },
  beforeDestroy () {
    window.clearInterval(intervalId);
    if (ws) {
      ws.close()
      ws = null
    }
  },
  mounted () {
    lineChart = this.$echarts.init(document.getElementById('nate'))
    // iqLineChart = this.$echarts.init(document.getElementById('iq'))
    // this.getOccupancyData()
    // window.setInterval(() => {
    //   setTimeout(this.getOccupancyData(), 0)
    // }, 10000)
  },
  created () {
    axios.get('http://47.118.20.181:8080/box').then(response => {
      if (Object.keys(response.data).length != 0) {
        console.log('盒子设备的信息 -> ', JSON.stringify(response.data))
        this.boxInfos = response.data
        this.formItem.mfid = this.boxInfos[0].mfid
        this.mfid = this.formItem.mfid
        this.iqMfid = this.boxInfos[0].mfid
        let notifyMsg = '当前设备站点id是:' + this.formItem.mfid
        this.$baseNotify(notifyMsg, '提示', 'success', 'bottom-right')
        this.init()
      }
    })
  },
  activated () {

  },
  methods: {
    init () {
      //调接口判断设备当前占用状态
      this.getBoxStatus()

      console.log('当前用户权限 -> ' + JSON.stringify(this.permissions))
      if (this.permissions[0] == 'user') {
        this.ifEditable = true
        this.ifNormalUserHide = false
      }
      if (this.permissions[0] == 'admin') {
        this.ifEditable = false
        this.ifNormalUserHide = true
      }

      axios.get('http://47.118.20.181:8080/scan?mfid=' + this.formItem.mfid).then(res => {
        console.log('当前设备配置参数 -> ', JSON.stringify(res.data))
        this.formItem.startfreq = res.data.start
        this.formItem.stopfreq = res.data.stop
        this.formItem.step = res.data.step
      })
    },
    refreshBoxStatus () {
      this.init()
    },
    getBoxStatus () {
      axios.get('http://47.118.20.181:8080/rf/status?mfid=' + this.formItem.mfid).then(response => {
        //响应里的data为空,说明没有正在进行的任务,可以进行扫描指令
        if (Object.keys(response.data).length == 0) {
          this.ifView = false
        }
        //不为空,说明有正在执行的任务,只能查看
        else {
          if (isEmpty(response.data.data)) {
            this.ifView = false
          } else {
            this.ifView = true
          }
        }
        // this.start()
        // this.getTransportNumData()
      })
    },
    saveSpectrumNumConfig () {
      axios.post('http://47.118.20.181:8080/scan?mfid=' + this.formItem.mfid + '&start=' + this.formItem.startfreq + '&stop=' + this.formItem.stopfreq + '&step=' + this.formItem.step).then(res => {
        console.log('saveSpectrumNumConfig -> ', JSON.stringify(res.data))
      })
    },
    iqNumsScrollFun (startNum, maxNum) {
      let that = this;
      let numText = Number(startNum);
      let golb; // 为了清除requestAnimationFrame;
      let addNum = 100;
      if ((Number(maxNum) - Number(startNum)) % 20 != 0) {
        addNum = Math.ceil((Number(maxNum) - Number(startNum)) / 20);
      } else {
        addNum = (Number(maxNum) - Number(startNum)) / 20;
      }
      // console.log(startNum,maxNum,addNum)
      function numSlideFun () {
        // 数字动画
        numText += addNum; // 速度的计算可以为小数 。数字越大，滚动越快
        if (numText >= maxNum) {
          numText = maxNum;
          cancelAnimationFrame(golb);
          // clearInterval(golb);
        } else {
          golb = requestAnimationFrame(numSlideFun);
          // golb = setInterval(numSlideFun,50);
        }
        that.iqNums = Number(numText);
        // console.log(numText)
      }
      numSlideFun(); // 调用数字动画
    },
    spectrumNumsScrollFun (startNum, maxNum) {
      let that = this;
      let numText = Number(startNum);
      let golb; // 为了清除requestAnimationFrame;
      let addNum = 100;
      if ((Number(maxNum) - Number(startNum)) % 20 != 0) {
        addNum = Math.ceil((Number(maxNum) - Number(startNum)) / 20);
      } else {
        addNum = (Number(maxNum) - Number(startNum)) / 20;
      }
      // console.log(startNum,maxNum,addNum)
      function numSlideFun () {
        // 数字动画
        numText += addNum; // 速度的计算可以为小数 。数字越大，滚动越快
        if (numText >= maxNum) {
          numText = maxNum;
          cancelAnimationFrame(golb);
          // clearInterval(golb);
        } else {
          golb = requestAnimationFrame(numSlideFun);
          // golb = setInterval(numSlideFun,50);
        }
        that.spectrumNums = Number(numText);
        // console.log(numText)
      }
      numSlideFun(); // 调用数字动画
    },
    //统计展示1分钟内,IQ数据传输量,频谱数据传输量
    getTransportNumData () {
      let self = this
      axios.get('http://47.118.20.181:8080/rf/transport?mfid=' + this.formItem.mfid).then(res => {
        //判断响应的data是否为空
        if (!isEmpty(res.data)) {
          const allData = res.data;
          // console.log('getTransportNumData ->', JSON.stringify(allData))
          if (allData.subtype == 'spec') {
            // this.spectrumNums = parseInt(parseInt(allData.data) / 1000)
            self.spectrumNumsScrollFun(
              self.spectrumNums,
              Number(parseInt(parseInt(allData.data) / 1000))
            );
            this.iqNums = 0
          }
          else if (allData.subtype == 'iq') {
            // this.iqNums = parseInt(parseInt(allData.data) / 1000)
            self.iqNumsScrollFun(self.iqNums,
              Number(parseInt(parseInt(allData.data) / 1000)))
            this.spectrumNums = 0
          }
        }
        else {

        }

      }
      )
    },
    getOccupancyData () {
      let dom = document.getElementById('occupancy')
      let myChart = this.$echarts.init(dom)
      myChart.showLoading({
        text: '加载中...请稍后',
        color: '#47B485',
        textColor: '#000',
        maskColor: 'rgba(255, 255, 255, 0.8)',
        zlevel: 0
      })
      axios.get('http://47.118.20.181:8080/rf/occupancy').then(response => {
        //判断响应的data是否为空
        if (!isEmpty(response.data)) {
          // console.log('occupancy -> ', JSON.stringify(response.data))
          let [xAxis, occupanyTrace] = onRecordsOccupancy(response.data)
          this.occupancyNums = (Number(response.headers['content-length']) / 1024).toFixed(2)
          this.occupancyOptions = {
            title: {
              text: '占用度',
              left: 'center',
            },
            // backgroundColor: 'black',
            // darkMode: true,
            tooltip: {
              trigger: 'axis',
            },
            legend: {
              show: true,
              data: ['占用度'],
              left: 'left',
              formatter: function (name) {
                return name + '(' + '%' + ')'
              },
            },
            xAxis: {
              data: xAxis,
              axisLabel: {
                // eslint-disable-next-line no-unused-vars
                formatter: function (value, index) {
                  return value + 'MHz'
                },
              },
            },
            yAxis: {
              type: 'value',
            },
            dataZoom: [
              {   // 这个dataZoom组件，默认控制x轴。
                type: 'slider', // 这个 dataZoom 组件是 slider 型 dataZoom 组件
                start: 0,      // 左边在 10% 的位置。
                end: 100         // 右边在 60% 的位置。
              }
            ],
            series: [
              {
                name: '占用度',
                type: 'line',
                data: occupanyTrace,
              }
            ],
          }
          myChart.hideLoading()
          myChart.setOption(this.occupancyOptions)
        }
        else {
          const dom = document.getElementById('occupancy')
          dom.innerHTML = '暂无数据'
          dom.removeAttribute('_echarts_instance_')
          this.$baseMessage('暂无数据', 'warning')
          return
        }

      }
      )
    },
    start () {
      this.$refs['requestForm'].validate((valid) => {
        if (valid) {
          intervalId = window.setInterval(() => {
            setTimeout(this.getTransportNumData(), 0)
          }, 1000)
          this.drawSpectrumChart()
          //保存输入框里的参数配置 起始频率 终止频率
          this.saveSpectrumNumConfig()
        } else {
          console.log('requestForm验证失败 !!')
          return false
        }
      })
    },
    drawSpectrumChart () {
      let vm = this
      if (ws) {
        console.log('WebSocket未关闭 先调用频谱关闭函数...')
        this.stop()
      }
      this.iqNums = 0
      this.getTransportNumData()
      console.log('开始连接Ws')
      this.isStartBtnDisabled = true
      this.isStopBtnDisabled = true
      setTimeout(() => {
        this.isStopBtnDisabled = false
      }, 3000)
      // ws = new WebSocket("ws://127.0.0.1:6003/ws");
      ws = new WebSocket('ws://47.118.20.181:6004/ws') //公网
      // ws = new WebSocket('ws://192.168.0.193:6004/ws')
      let obj = {}
      if (this.ifView) {
        obj = {
          mfid: this.formItem.mfid,
          cmd: 'view'
        }
      }
      else {
        obj = {
          mfid: this.formItem.mfid,
          cmd: 'start',
          type: 'B_PScan',
          startfreq: parseInt(vm.formItem.startfreq * 1000000),
          stopfreq: parseInt(vm.formItem.stopfreq * 1000000),
          step: parseInt(vm.formItem.step),
          mode: "boer"
        }
      }
      ws.onopen = function (evt) {
        console.log('波尔实时调用websocket连接已打开...')
        // heartHandler = setInterval(() => {
        //   ws.send('keepalive')
        // }, 3000)
        lineChart.showLoading({
          text: '加载中...请稍后',
          color: '#47B485',
          textColor: '#000',
          maskColor: 'rgba(255, 255, 255, 0.8)',
          zlevel: 0
        })
        let cmd = JSON.stringify(obj)
        console.log('cmd:', cmd)
        ws.send(cmd)
      }.bind(this)

      ws.onmessage = function (evt) {
        console.log('##########频谱图表收到信息#############')
        lineChart.hideLoading()
        let traceData = evt.data
        let traceDataObj = JSON.parse(traceData)
        //console.log(traceData)
        if (traceDataObj.type == 'status' || traceDataObj.type == undefined) {
          return
        }
        if (traceDataObj.bizResText != undefined && traceDataObj.bizResText != 'ok') {
          console.log('状态:', JSON.stringify(traceDataObj))
          vm.$baseMessage(traceDataObj.bizResText, 'error')
          vm.isStartBtnDisabled = false
          vm.isStopBtnDisabled = true
        } else {
          let [x, y, xHis, yHis] = onRecords(traceData)
          // console.log('x ->', JSON.stringify(x))
          // console.log('y ->', JSON.stringify(y))

          let unit = 'dBm'
          this.orgOptions = {
            backgroundColor: '#000000',
            title: {
              text: '波尔频谱实时调用',
              left: 'center',
              textStyle: {
                fontWeight: 'normal',//标题颜色
                color: '#FFFFFF'
              }
            },
            // backgroundColor: 'black',
            // darkMode: true,
            tooltip: {
              trigger: 'axis',
            },
            legend: {
              show: true,
              data: ['强度'],
              left: 'left',
              textStyle: { //图例文字的样式
                color: '#ffffff',
                fontSize: 16
              },
              formatter: function (name) {
                return name + '(' + unit + ')'
              },
            },
            xAxis: {
              data: x,
              axisLabel: {
                textStyle: {
                  color: '#FFFFFF',  //更改坐标轴文字颜色
                  fontSize: 14      //更改坐标轴文字大小
                },
                formatter: function (value, index) {
                  return value + 'MHz'
                },
              },
              axisLine: {
                lineStyle: {
                  color: '#FFFFFF' //更改坐标轴颜色
                }
              }
            },
            yAxis: {
              type: 'value',
              //纵轴刻度最小值写死为-100
              // min: function (value) {
              //   return -95
              // },
              //纵轴刻度最大值写死为-30
              // max: function (value) {
              //   return -50
              // },
              scale: true, //自适应
              axisLabel: {
                textStyle: {
                  color: '#FFFFFF',  //更改坐标轴文字颜色
                  fontSize: 14      //更改坐标轴文字大小
                }
              },
              axisLine: {
                lineStyle: {
                  color: '#FFFFFF' //更改坐标轴颜色
                }
              }
            },
            series: [
              {
                name: '强度',
                type: 'line',
                data: y,
                lineStyle: {
                  "color": "#99FF66",
                  "width": 2
                }
              },
            ],
            dataZoom: [
              {   // 这个dataZoom组件，默认控制x轴。
                type: 'slider', // 这个 dataZoom 组件是 slider 型 dataZoom 组件
                start: 0,      // 左边在 10% 的位置。
                end: 100         // 右边在 60% 的位置。
              }
            ],
          }

          lineChart.setOption(this.orgOptions)
        }
      }

      ws.onclose = function (evt) {
        lineChart.hideLoading()
        console.log('波尔实时调用websocket连接已关闭...')
      }
    },
    setBtnStat () {
      this.isStartBtnDisabled = true
      this.isStopBtnDisabled = true
      setTimeout(() => {
        this.isStartBtnDisabled = false
      }, 3000)
    },
    stop () {
      this.setBtnStat()
      // this.$baseNotify('当前频谱图状态ifView -> ' + this.ifView, '代码提示', 'success', 'bottom-right')
      if (this.ifView) {
        window.clearInterval(intervalId);
        if (ws) {
          ws.close()
          ws = null
        }
      }
      else {
        this.cmdStop()
      }
    },
    cmdStop () {
      this.setBtnStat()
      let obj = { cmd: 'stop', mfid: this.formItem.mfid }
      let cmd = JSON.stringify(obj)
      ws.send(cmd)
      if (heartHandler) {
        clearInterval(heartHandler)
        heartHandler = null
      }
      if (ws) {
        ws.close()
        ws = null
      }
      this.ifView = false
    },
    resume () {
      if (ws) {
        ws.close()
        ws = null
      }
      this.$router.push({
        path: '/middle-index'
      })
    },
    startIQ () {
      if (ws) {
        console.log('WebSocket未关闭 先调用频谱关闭函数...')
        this.stop()
      }
      this.spectrumNums = 0
      intervalId = window.setInterval(() => {
        setTimeout(this.getTransportNumData(), 0)
      }, 1000)
      console.log('开始连接IQ数据 Ws')
      this.isStartIQDisabled = true
      this.isStopIQDisabled = true
      setTimeout(() => {
        this.isStopIQDisabled = false
      }, 5000)
      // ws = new WebSocket("ws://127.0.0.1:6003/ws");
      ws = new WebSocket('ws://47.118.20.181:6004/ws') //公网
      // ws = new WebSocket('ws://192.168.0.193:6004/ws')
      let obj = {}

      obj = {
        mfid: this.iqMfid,
        cmd: 'start',
        type: 'B_SglFreqMeas',
        frequency: this.freqSingleMeasure,
        span: 244141,
      }

      ws.onopen = function (evt) {
        console.log('波尔IQ实时调用websocket连接已打开...')
        // heartHandler = setInterval(() => {
        //   ws.send('keepalive')
        // }, 3000)
        iqLineChart.showLoading({
          text: '加载中...请稍后',
          color: '#47B485',
          textColor: '#000',
          maskColor: 'rgba(255, 255, 255, 0.8)',
          zlevel: 0
        })
        let cmd = JSON.stringify(obj)
        ws.send(cmd)
      }.bind(this)

      ws.onmessage = function (evt) {
        console.log('##########IQ图表收到信息#############')
        iqLineChart.hideLoading()
        let traceData = evt.data
        let traceDataObj = JSON.parse(traceData)
        //console.log(traceData)
        if (traceDataObj.bizResText != undefined) {
          console.log('状态:', traceDataObj.bizResText)
        } else {
          let [x, yIdata, yQdata] = onRecordsIq(traceData)
          let unit = 'mv(毫伏)'
          this.iqLineOptions = {
            title: {
              text: '波尔IQ实时调用',
              left: 'center',
            },
            // backgroundColor: 'black',
            // darkMode: true,
            tooltip: {
              trigger: 'axis',
            },
            legend: {
              show: true,
              data: ['I数据', 'Q数据'],
              left: 'left',
              formatter: function (name) {
                return name + '(' + unit + ')'
              },
            },
            xAxis: {
              data: x,
              axisLabel: {
                formatter: function (value, index) {
                  return value + 'us(微秒)'
                },
              },
            },
            yAxis: {
              type: 'value',
            },
            series: [
              {
                name: 'I数据',
                type: 'line',
                data: yIdata,
              },
              {
                name: 'Q数据',
                type: 'line',
                data: yQdata,
              }
            ],
            dataZoom: [
              {   // 这个dataZoom组件，默认控制x轴。
                type: 'slider', // 这个 dataZoom 组件是 slider 型 dataZoom 组件
                start: 0,      // 左边在 10% 的位置。
                end: 100         // 右边在 60% 的位置。
              }
            ],
          }

          iqLineChart.setOption(this.iqLineOptions)
        }
      }

      ws.onclose = function (evt) {
        iqLineChart.hideLoading()
        console.log('波尔IQ实时调用websocket连接已关闭...')
      }
    },
    stopIQ () {
      this.isStartIQDisabled = true
      this.isStopIQDisabled = true
      window.clearInterval(intervalId);
      setTimeout(() => {
        this.isStartIQDisabled = false
      }, 5000)
      let obj = { cmd: 'stop', mfid: this.iqMfid, }
      let cmd = JSON.stringify(obj)
      ws.send(cmd)
      if (heartHandler) {
        clearInterval(heartHandler)
        heartHandler = null
      }
      if (ws) {
        ws.close()
        ws = null
      }
    }
  },
}

function onRecordsIq (_data) {
  let { idata, centerfreq, qdata, span, type, ts } = JSON.parse(_data)
  // console.log('onRecordsIq 类型 - >', type)
  //如果是IQ数据才进行处理
  if (type == 'IQ') {
    let idataTrace = idata.split(',')
    let qdataTrace = qdata.split(',')
    let xAxis = []
    let dataLength = idataTrace.length
    for (let i = 0; i < dataLength; i++) {
      xAxis.push(
        parseInt((i / parseFloat(span)) * dataLength * 100000)
      )
    }
    return [xAxis, idataTrace, qdataTrace]
  }
}

function onRecords (_data) {
  let { current, history, type, startfreq, stepfreq } = JSON.parse(_data)
  // console.log('onRecord 类型 - >', type, startfreq, stepfreq)
  //如果是频谱数据才进行处理
  if (type == 'spectrum') {
    let currentTrace = current.data.split(',')
    let freqPoint = []
    let pointCount = currentTrace.length
    for (let i = 0; i < pointCount; i++) {
      //原子封装接口返回的数据大了10倍 因此此处需要进行处理 并转换为dBm值-107
      currentTrace[i] = parseFloat(parseFloat(currentTrace[i]) / 10 - 107)
      freqPoint.push(
        parseInt((parseInt(startfreq) + i * parseInt(stepfreq)) / 1000000)
      )
    }
    // console.log('x 轴数据 - >', JSON.stringify(freqPoint))
    // console.log('y 轴数据 - >', JSON.stringify(currentTrace))
    let historyTrace = []
    // for (let item of history) {
    //   // console.log('history -> ', item)
    //   let itemData = null
    //   if (item.data != undefined) {
    //     itemData = item.data.split(',')
    //     historyTrace = historyTrace.concat(itemData)
    //   }
    // }

    let freqPointHis = []
    // let pointCountHis = historyTrace.length
    // for (let i = 0; i < pointCountHis; i++) {
    //   historyTrace[i] = parseFloat(historyTrace[i]) / 10
    //   freqPointHis.push(
    //     (parseInt(history[0].startfreq) + i * parseInt(history[0].stepfreq)) /
    //     1000000
    //   )
    // }
    return [freqPoint, currentTrace, freqPointHis, historyTrace]
  }
}

function onRecordsOccupancy (_data) {
  let { data } = _data
  let xAxis = []
  let traceOccupancy = []
  let pointCount = data.length
  for (let i = 0; i < pointCount; i++) {
    let { frequency, occupancy } = data[i]
    xAxis.push(parseInt(frequency / 1000000))
    traceOccupancy.push(parseInt(occupancy))
  }
  return [xAxis, traceOccupancy]
}
</script>

<style scoped>
.right-condition {
  margin-top: 7vh;
}

.left-condition {
  margin-top: 3vh;
}

.earn-title {
  width: 100%;
}

.ring-name {
  background-image: -webkit-linear-gradient(
    270deg,
    #1be5ad 0%,
    rgba(35, 167, 229, 0.82) 98%
  );
  font-size: 14px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.ring-numbers {
  background-color: rgba(232, 59, 70, 0);
  display: inline-block;
  letter-spacing: 0.02em;
  text-indent: 0.02em;
  word-break: break-all;
  text-align: center;
  height: auto;
  line-height: normal;
  font-size: 24px;
  font-weight: bolder;
  letter-spacing: 0.02em;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-image: -webkit-linear-gradient(
    270deg,
    #1be5ad 0%,
    rgba(35, 167, 229, 0.82) 98%
  );
}
</style>
